package common.util;

import common.model.dto.Fraction;
import org.apache.commons.math3.fraction.BigFraction;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;

/**
 * 描述
 *
 * @author 米泽鹏
 * @since 2023-11-30 下午 5:54
 */
public class BigFractionUtil {

	public static BigFraction valueOf(BigDecimal d) {
		return new BigFraction(
				d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
				d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale())
		);
	}

	public static BigFraction valueOf(BigFraction numerator, BigFraction denominator) {
		return new BigFraction(
				numerator.getNumerator().multiply(denominator.getDenominator()),
				numerator.getDenominator().multiply(denominator.getNumerator())
		);
	}

	public static BigFraction valueOf(BigDecimal numerator, BigDecimal denominator) {
		return valueOf(valueOf(numerator), valueOf(denominator));
	}

	public static Fraction toFraction(BigFraction fraction) {
		return new Fraction(fraction.getNumerator(), fraction.getDenominator());
	}

	/**
	 * 判断是否全部相等
	 */
	public static boolean isAllEquals(BigFraction... bigFractions) {
		if (bigFractions.length == 0) {
			throw new IllegalArgumentException("分数集合不能为空");
		}
		if (bigFractions.length == 1) {
			return true;
		}
		for (int i = 0; i < bigFractions.length; i++) {
			if (!bigFractions[i].equals(bigFractions[i + 1])) {
				return false;
			}
			if (i == bigFractions.length - 2) {
				break;
			}
		}
		return true;
	}

	/**
	 * 判断是否全部相等
	 */
	public static boolean isAllEquals(Collection<BigFraction> bigFractions) {
		if (bigFractions == null || bigFractions.isEmpty()) {
			throw new IllegalArgumentException("分数集合不能为空");
		}
		if (bigFractions.size() == 1) {
			return true;
		}
		return isAllEquals(bigFractions.toArray(new BigFraction[0]));
	}

}
